const mongoose = require('mongoose')
const config = require('./config')

module.exports = function(successCallback, errorCallback = () => {}) {
  if(typeof successCallback !== 'function') {
    console.log('传入的第一个参数应该是一个成功回调函数')
    return
  }

  if(typeof errorCallback !== 'function') {
    console.log('传入的第二个参数应该是一个失败回调函数')
    return
  }

  mongoose.connect(`mongodb://${config.DBHOST}:${config.DBPOST}/${config.DBNAME}`).then(() => {
    successCallback()
  }).catch(error => {
    errorCallback(error)
  })

  mongoose.connection.on('error', error => {
    errorCallback(error)
  })

  mongoose.connection.on('disconnected', () => {
    errorCallback({ message: '失去连接错误' })
  })
}